<script setup>
	import { h, ref } from 'vue'
	import { PlusOutlined } from '@ant-design/icons-vue'
	import ConnectorTypeModal from './ConnectorTypeModal.vue'
	import DataConnectorForm from './DataConnectorForm.vue'
	import dataConnectorApi from '@/views/plugin/dashboard/api/dataConnectorApi'

	const props = defineProps({
		onConnectorSelect: {
			type: Function,
			required: true
		}
	})
	const dataConnectorFormRef = ref(null)
	const cardLoading = ref(true)
	const treeData = ref([])
	const showModal = ref(false)
	const onSelect = (keys, info) => {
		if (info.node.isLeaf) {
			props.onConnectorSelect(info.node)
		}
	}

	const handleTypeSelect = (type) => {
		// 打开对应类型的连接器配置表单
		dataConnectorFormRef.value.open({ type: type.key })
	}

	// 加载左侧的树
	const loadTreeData = () => {
		dataConnectorApi
			.list()
			.then((res) => {
				cardLoading.value = false
				if (res !== null) {
					// 清空现有树数据
					treeData.value = []
					nextTick(() => {
						// 先按照res的type进行分类，然后装成示例treeData的结构
						const typeMap = {}
						res.forEach((item) => {
							if (!typeMap[item.type]) {
								typeMap[item.type] = []
							}
							typeMap[item.type].push(item)
						})
						for (const type in typeMap) {
							const connectors = typeMap[type]
							const children = connectors.map((connector) => {
								return {
									title: connector.name,
									key: connector.id,
									isLeaf: true,
									data: connector
								}
							})
							treeData.value.push({
								title: type,
								key: type,
								children: children
							})
						}
					})
				}
			})
			.finally(() => {
				cardLoading.value = false
			})
	}
	onMounted(() => {
		loadTreeData()
	})

	// 暴露方法给父组件
	defineExpose({
		loadTreeData
	})
</script>

<template>
	<div class="w-64 border-r p-6 overflow-auto">
		<div class="flex justify-between items-center mb-4">
			<div class="text-xl font-semibold">连接器</div>
			<a-button size="small" :icon="h(PlusOutlined)" @click="showModal = true" />
			<ConnectorTypeModal :visible="showModal" :onClose="() => (showModal = false)" :onSelect="handleTypeSelect" />
		</div>
		<a-directory-tree multiple :treeData="treeData" @select="onSelect" defaultExpandAll />
		<DataConnectorForm ref="dataConnectorFormRef" />
	</div>
</template>
